package com.biostime.terminal.util;

import java.util.LinkedList;
import java.util.List;

/**
* <p>
* 负责query的转换
* </p>
*
* @author yangrzh 2014/7/7
*/
public class QueryUtil {

    /**
     * 通过qid和pid，把树结构的querys转成List结构
     *
     * @param source
     * @param id
     * @return
     */
    public static List<com.biostime.terminal.vo.service.Query> handleQuery(List source, final QueryCounter id) {
        List<com.biostime.terminal.vo.service.Query> returnList = new LinkedList<com.biostime.terminal.vo.service.Query>();

        // 前一个query，父query的id
        int pid = id.get();

        for (Object o : source) {
            // 当前query的id
            id.add();

            com.biostime.terminal.vo.service.Query tempQuery = (com.biostime.terminal.vo.service.Query) o;
            tempQuery.setQid(id.get());
            tempQuery.setPid(pid);
            returnList.add(tempQuery);

            List tempSource = tempQuery.getQueryList();
            if (tempSource != null && tempSource.size() > 0) {
                List<com.biostime.terminal.vo.service.Query> tempReturnList = handleQuery(tempSource, id);
                returnList.addAll(tempReturnList);
                // 客户端的queryList经常是复用的，不能改变query的内容
//                tempQuery.setQueryList(null);
            }
        }
        return returnList;
    }

    /**
     * 用于计算Query的id
     */
    static class QueryCounter {

        private int id;

        QueryCounter(int id) {
            this.id = id;
        }

        public void add() {
            id++;
        }

        public int get() {
            return id;
        }

    }

}
